package com.webemail.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.webemail.sys.model.SysEmailAccount;
import com.webemail.sys.model.SysFolder;
import com.webemail.sys.model.SysLabel;
import com.webemail.sys.model.SysLabelMessage;
import com.webemail.sys.model.SysMessageDrafts;
import com.webemail.sys.model.SysMessageFolder;
import com.webemail.sys.model.SysMessageSend;
import com.webemail.sys.service.EmailService;
import com.webemail.sys.service.FolderService;
import com.webemail.sys.service.LabelMessageService;
import com.webemail.sys.service.LabelService;
import com.webemail.sys.service.MessageDeletedService;
import com.webemail.sys.service.MessageDraftsService;
import com.webemail.sys.service.MessageFolderService;
import com.webemail.sys.service.MessageInboxService;
import com.webemail.sys.service.MessageJunkService;
import com.webemail.sys.service.MessageSendService;
import com.webemail.sys.util.CommonUtils;
import com.webemail.sys.util.LayuiBean;
import com.webemail.sys.util.MailBean;
import com.webemail.sys.util.MailConnect;
import com.webemail.sys.util.MailConnect.FolderType;
import com.webemail.sys.util.MailContent;
import com.webemail.sys.util.MailFolder;
import com.webemail.sys.util.MailSender;
import com.webemail.sys.util.MailUtils;
import com.webemail.sys.util.ResultBean;

import cn.hutool.core.util.ObjectUtil;

@Controller
@RequestMapping("/drafts")
public class EmailDraftsController {
	@Resource
	private EmailService emailService;
	@Resource
	private FolderService folderService;
	@Resource
	private LabelMessageService labelMessageService;
	@Resource
	private LabelService labelService;
	@Resource
	private MessageDeletedService messageDeletedService;
	@Resource
	private MessageDraftsService messageDraftsService;
	@Resource
	private MessageFolderService messageFolderService;
	@Resource
	private MessageInboxService messageInboxService;
	@Resource
	private MessageJunkService messageJunkService;
	@Resource
	private MessageSendService messageSendService;

	private Logger logger = LoggerFactory.getLogger(getClass());
	private static String saveURL = "http://localhost:8080/mail";
	private static String saveFolder = "uploadFiles";
	private static String folderName = "草稿箱";

	private int getUserId() {
		return 1;
	}

	private SysMessageDrafts toSysMessageDrafts(MailContent content, long userId, long mailId, String folder,
			boolean isDefaultFolder, long folderId, boolean saveAttachment, String path) {
		SysMessageDrafts temp = new SysMessageDrafts();
		temp.setUserId(userId);
		temp.setMailId(mailId);
		temp.setFolder(folder);
		temp.setFolderId(folderId);
		temp.setMessageId(content.getMessageId());
		temp.setSubject(content.getSubject());
		temp.setBodyText(content.getBodyText());
		temp.setSentDate(CommonUtils.getDateStr(content.getSentDate()));
		temp.setSentDateTime(content.getSentDate().getTime() + "");
		temp.setSize((long) content.getSize());
		temp.setMailFrom(content.getFrom());
		temp.setMailAddress(content.getMailAddressStr());
		temp.setMailCopyto(content.getCopyToStr());
		temp.setMailBCopyto(content.getBCopyToStr());
		if (content.isHasAttachMent()) {
			temp.setHasAttachment("true");
		} else {
			temp.setHasAttachment("false");
		}
		if (ObjectUtil.isNotEmpty(temp.getAttachment()) && saveAttachment) {
			content.saveAttachment(
					path + "\\" + EmailDraftsController.saveFolder + "\\" + userId + "\\" + mailId + "\\");
			ArrayList<String> fileNames = content.getFileNames();
			String[] fileUrls = new String[fileNames.size()];
			for (int i = 0; i < fileNames.size(); i++) {
				fileUrls[i] = EmailDraftsController.saveURL + "/" + EmailDraftsController.saveFolder + "/" + userId
						+ "/" + mailId + "/" + fileNames.get(i);
			}
			temp.setAttachment(StringUtils.join(fileUrls, ","));
		}
		if (content.isNew()) {
			temp.setHasRead("false");
		} else {
			temp.setHasRead("true");
		}
		if (isDefaultFolder) {
			temp.setIsDefaultFolder("true");
		} else {
			temp.setIsDefaultFolder("false");
		}
		temp.setHasReply("false");
		temp.setLabel("");
		temp.setSource(false);
		temp.setState((long) 0);
		return temp;
	}

	@RequestMapping("/page")
	@ResponseBody
	public String page(HttpServletRequest request, Model model) {
		String colomn = CommonUtils.getString(request.getParameter("colomn"));
		String word = CommonUtils.getString(request.getParameter("word"));
		long userId = this.getUserId();
		int page = 0;
		int limit = 10;
		LayuiBean<SysMessageDrafts> layuiBean;
		try {
			page = Integer.parseInt(CommonUtils.getString(request.getParameter("page")));
		} catch (Exception e) {
			e.printStackTrace();
			page = 0;
		}
		if (page > 0) {
			page--;
		}
		try {
			limit = Integer.parseInt(CommonUtils.getString(request.getParameter("limit")));
		} catch (Exception e) {
			e.printStackTrace();
			limit = 10;
		}

		List<SysMessageDrafts> result = messageDraftsService.listByPage(userId,colomn,word,page * limit, limit, 0, 2);
		long size = messageDraftsService.count(userId,colomn,word, 0, 2);
		layuiBean = new LayuiBean<>(0, "SUCC", size, result);
		return JSON.toJSONString(layuiBean);
	}

	@RequestMapping("/refresh")
	@ResponseBody
	public String refresh(HttpServletRequest request, Model model) {
		String path = request.getSession().getServletContext().getRealPath("/");
		long userId = this.getUserId();
		List<SysEmailAccount> mails = null;
		try {
			mails = emailService.list(userId);
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
		}
		if (mails == null || mails.size() < 1) {
			return JSON.toJSONString(new ResultBean(0, "没有添加邮箱", null));
		}
		for (int key = 0; key < mails.size(); key++) {
			SysEmailAccount temp = mails.get(key);
			long mailId = temp.getId();
			try {
				MailBean re = null;
				MailConnect mailConnect = null;
				try {
					re = MailUtils.getReMailBean(temp);
					mailConnect = new MailConnect(re);
					mailConnect.checkProperties();
				} catch (Exception e) {
					e.printStackTrace();
					return JSON.toJSONString(new ResultBean(0, e.getMessage(), null));
				}
				if (mailConnect.getState() != 0) {
					return JSON.toJSONString(new ResultBean(0, mailConnect.getErrorMsg(), null));
				}
				mailConnect.init();
				Folder folder = mailConnect.getDraftsFolder();
				MailFolder mailFolder = new MailFolder(folder);
				ArrayList<MailContent> mailContent = mailFolder.getMailContent();
				List<SysMessageDrafts> messageSends = messageDraftsService.list(mailId, userId);
				ArrayList<SysMessageDrafts> addMessage = new ArrayList<SysMessageDrafts>();
				for (int i = 0; i < mailContent.size(); i++) {
					MailContent mailContentObject = mailContent.get(i);
					boolean flag = true;
					for (int j = 0; j < messageSends.size(); j++) {
						SysMessageDrafts messageSendObj = messageSends.get(j);
						if (mailContentObject.getFrom().trim().equalsIgnoreCase(messageSendObj.getMailFrom().trim())
								&& messageSendObj.getSentDateTime()
										.equals(String.valueOf(mailContentObject.getSentDate().getTime()))) {
							flag = false;
							break;
						}
					}
					if (flag) {
						// 保存邮件
						addMessage.add(this.toSysMessageDrafts(mailContentObject, userId, mailId, folderName, true, 0,
								false, path));
					}
				}
				mailConnect.stop();
				if (addMessage.size() > 0) {
					messageDraftsService.insert(addMessage);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return JSON.toJSONString(new ResultBean(1, "刷新成功", null));
	}

	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpServletRequest request, Model model) {
		CommonUtils.print(request);
		int userId = this.getUserId();
		String sendmail = CommonUtils.getString(request.getParameter("sendmail"));
		int mailId = Integer.parseInt(sendmail);
		String draftsId = CommonUtils.getString(request.getParameter("id"));
		String remail = CommonUtils.getString(request.getParameter("remail"));
		String copyto = CommonUtils.getString(request.getParameter("copyto"));
		String bcopyto = CommonUtils.getString(request.getParameter("bcopyto"));
		String subject = CommonUtils.getString(request.getParameter("subject"));
		String bodytext = CommonUtils.getString(request.getParameter("bodytext"));
		boolean priority = CommonUtils.getString(request.getParameter("priority")).equalsIgnoreCase("true");
		boolean notification = CommonUtils.getString(request.getParameter("notification")).equalsIgnoreCase("true");
		SysEmailAccount sysEmailAccount = emailService.get(mailId, userId);
		SysMessageDrafts bean = new SysMessageDrafts();
		
		try{
			bean.setId(Long.parseLong(draftsId));
		}catch(Exception e){
			return JSON.toJSONString(new ResultBean(0, "保存失败"));
		}
		bean.setUserId((long) userId);
		bean.setMailId((long) mailId);
		bean.setFolder("草稿箱");
		bean.setFolderId((long) 0);
		bean.setSubject(subject);
		bean.setBodyText(bodytext);
		bean.setMailFrom(sysEmailAccount.getAccount());
		bean.setMailAddress(remail);
		bean.setMailCopyto(copyto);
		bean.setMailBCopyto(bcopyto);
		String file[] = request.getParameterValues("file[]");
		if (file != null && file.length > 0) {
			bean.setHasAttachment("true");
			bean.setAttachment(StringUtils.join(file, ","));
		} else {
			bean.setHasAttachment("false");
		}
		bean.setHasRead("true");
		bean.setIsDefaultFolder("true");
		bean.setHasReply("false");
		bean.setLabel("");
		bean.setSource(true);
		if (priority) {
			bean.setPriority("true");
		} else {
			bean.setPriority("false");
		}
		if (notification) {
			bean.setNotification("true");
		} else {
			bean.setNotification("false");
		}
		bean.setState((long) 0);
		if (messageDraftsService.update(bean) >= 0) {
			return JSON.toJSONString(new ResultBean(1, "保存成功"));
		} else {
			return JSON.toJSONString(new ResultBean(0, "保存失败"));
		}
	}

	@RequestMapping("/send")
	@ResponseBody
	public String send(HttpServletRequest request, Model model) {
		int userId = this.getUserId();
		String sendmail = CommonUtils.getString(request.getParameter("sendmail"));
		int mailId = Integer.parseInt(sendmail);
		String draftsId = CommonUtils.getString(request.getParameter("id"));
		String remail = CommonUtils.getString(request.getParameter("remail"));
		String copyto = CommonUtils.getString(request.getParameter("copyto"));
		String bcopyto = CommonUtils.getString(request.getParameter("bcopyto"));
		String subject = CommonUtils.getString(request.getParameter("subject"));
		String bodytext = CommonUtils.getString(request.getParameter("bodytext"));
		boolean priority = CommonUtils.getString(request.getParameter("priority")).equalsIgnoreCase("true");
		boolean notification = CommonUtils.getString(request.getParameter("notification")).equalsIgnoreCase("true");
		String file[] = request.getParameterValues("file[]");
		String filePath = request.getSession().getServletContext().getRealPath("uploadFile/");
		if (file != null) {
			for (int i = 0; i < file.length; i++) {
				file[i] = filePath.substring(0, filePath.length() - 1)
						+ file[i].substring((saveURL + "/uploadFile/").length() - 1);
			}
		}
		SysEmailAccount sysEmailAccount = emailService.get(mailId, userId);
		MailBean mailBean = MailUtils.getSendMailBean(sysEmailAccount);
		MailSender sender = new MailSender(mailBean);
		MimeMessage mimeMessage = sender.SendEmail(remail,copyto,bcopyto, subject, bodytext, file, priority, notification);
		// MailContent mailContent=new MailContent(mimeMessage);
		SysMessageSend result = new SysMessageSend();
		result.setUserId((long) userId);
		result.setMailId((long) mailId);
		result.setFolder("发件箱");
		result.setFolderId((long) 0);
		result.setSubject(subject);
		result.setBodyText(bodytext);
		try {
			result.setMessageId(mimeMessage.getMessageID());
			result.setSentDate(CommonUtils.getDateStr(mimeMessage.getSentDate()));
			result.setSentDateTime(String.valueOf(mimeMessage.getSentDate().getTime()));
			result.setSize((long) mimeMessage.getSize());
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		result.setMailFrom(mailBean.getAccount());
		result.setMailAddress(remail);
		result.setMailCopyto(copyto);
		result.setMailBCopyto(bcopyto);
		if (file != null && file.length > 0) {
			result.setHasAttachment("true");
		} else {
			result.setHasAttachment("false");
		}
		String fileUrls[] = request.getParameterValues("file[]");
		if (ObjectUtil.isNotEmpty(result.getAttachment()) && fileUrls != null && fileUrls.length > 0) {
			result.setAttachment(StringUtils.join(fileUrls, ","));
		}
		result.setHasRead("true");
		result.setIsDefaultFolder("true");
		result.setHasReply("false");
		result.setLabel("");
		result.setSource(true);
		result.setState((long) 0);
		messageSendService.insert(result);
		
		SysMessageDrafts temp=messageDraftsService.get(Integer.parseInt(draftsId), userId);
		temp.setState((long)4);
		messageDraftsService.update(temp);
		
		if (sender.getState() == 0) {
			return JSON.toJSONString(new ResultBean(1, "发送成功"));
		} else {
			return JSON.toJSONString(new ResultBean(0, sender.getErrorMsg()));
		}
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String emailDelete(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1) {
			return JSON.toJSONString(new ResultBean(0, "删除失败", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i].trim());
				SysMessageDrafts message = messageDraftsService.get(messageId, userId);
				if (message != null && message.getId() > 0) {
					message.setState((long) 1);
					if (messageDraftsService.update(message) > 0) {
						succIds.add(message.getId());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "删除成功", succIds));
		} else {

		}
		return JSON.toJSONString(new ResultBean(0, "删除失败", succIds));
	}

	@RequestMapping("/deleteAll")
	@ResponseBody
	public String emailDeleteAll(HttpServletRequest request, Model model) {

		String[] messageIds = null;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1) {
			return JSON.toJSONString(new ResultBean(0, "删除失败", null));
		}
		SysEmailAccount sysEmailAccount = null;
		MailConnect mailConnect = null;
		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i].trim());
				SysMessageDrafts message = messageDraftsService.get(messageId, userId);
				if (message != null && message.getId() > 0) {
					message.setState((long) 1);
					if (messageDraftsService.update(message) > 0) {
						succIds.add(message.getId());
						if (sysEmailAccount == null) {
							sysEmailAccount = emailService.get(message.getMailId(), userId);
						}
						if (mailConnect == null && sysEmailAccount != null && sysEmailAccount.getId() > 0) {
							mailConnect = new MailConnect(MailUtils.getReMailBean(sysEmailAccount));
							mailConnect.init();
						}
						if (mailConnect != null) {
							mailConnect.deleteMessage(FolderType.DraftsFolder, message.getMessageId(),
									message.getSentDateTime());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (mailConnect != null) {
			mailConnect.stop();
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "删除成功", succIds));
		} else {

		}
		return JSON.toJSONString(new ResultBean(0, "删除失败", succIds));
	}

	@RequestMapping("/moveFolder")
	@ResponseBody
	public String emailMoveFolder(HttpServletRequest request, Model model) {

		String[] messageIds = null;
		long folderId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			folderId = Long.parseLong(CommonUtils.getString(request.getParameter("folderId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || folderId < 1) {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
		SysFolder folder = folderService.get(folderId, userId);
		if (folder == null || folder.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "文件夹不存在", null));
		}

		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageDrafts message = messageDraftsService.get(messageId, userId);
				SysMessageFolder messageFolder = new SysMessageFolder();
				messageFolder.setUserId(userId);
				messageFolder.setMailId(message.getMailId());
				messageFolder.setFolder(folder.getName());
				messageFolder.setFolderId(folder.getId());
				messageFolder.setMessageId(message.getMessageId());
				messageFolder.setSubject(message.getSubject());
				messageFolder.setBodyText(message.getBodyText());
				messageFolder.setSentDate(message.getSentDate());
				messageFolder.setSentDateTime(message.getSentDateTime());
				messageFolder.setSize(message.getSize());
				messageFolder.setMailFrom(message.getMailFrom());
				messageFolder.setHasAttachment(message.getHasAttachment());
				messageFolder.setAttachment(message.getAttachment());
				messageFolder.setHasRead(message.getHasRead());
				messageFolder.setIsDefaultFolder("false");
				messageFolder.setHasReply(message.getHasReply());
				messageFolder.setLabel(message.getLabel());
				messageFolder.setSource(message.isLocalSource());
				messageFolder.setState((long) 0);
				messageFolderService.insert(messageFolder);
				message.setState((long) 3);
				messageDraftsService.update(message);
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "移动成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "移动失败", null));
		}
	}

	@RequestMapping("/addLabel")
	@ResponseBody
	public String emailAddLabel(HttpServletRequest request, Model model) {
		String[] messageIds = null;
		long labelId = 0;
		long userId = this.getUserId();
		ArrayList<Long> succIds = new ArrayList<Long>();
		try {
			messageIds = CommonUtils.getString(request.getParameter("messageIds")).trim().split(",");
			labelId = Long.parseLong(CommonUtils.getString(request.getParameter("labelId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageIds == null || messageIds.length < 1 || labelId < 1) {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
		SysLabel label = labelService.get(labelId, userId);
		for (int i = 0; i < messageIds.length; i++) {
			try {
				long messageId = Long.parseLong(messageIds[i]);
				SysMessageDrafts message = messageDraftsService.get(messageId, userId);
				SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
						folderName);
				if (labelMessage == null || labelMessage.getId() < 1) {
					labelMessage = new SysLabelMessage();
					labelMessage.setLabelId(label.getId() + "");
					labelMessage.setMessageId(message.getId() + "");
					labelMessage.setTable(folderName);
					labelMessage.setUserId(userId);
					labelMessageService.insert(labelMessage);
				}
				if (!CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
					if (StringUtils.isBlank(message.getLabel())) {
						message.setLabel(label.getName());
					} else {
						message.setLabel(message.getLabel() + "," + label.getName());
					}
					messageDraftsService.update(message);
				}
				succIds.add(message.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (succIds.size() > 0) {
			return JSON.toJSONString(new ResultBean(1, "添加成功", null));
		} else {
			return JSON.toJSONString(new ResultBean(0, "添加失败", null));
		}
	}

	@RequestMapping("/deleteLabel")
	@ResponseBody
	public String emailRemoveLabel(HttpServletRequest request, Model model) {
		long messageId = 0;
		String labelName = "";
		long userId = this.getUserId();
		try {
			messageId = Long.parseLong(CommonUtils.getString(request.getParameter("messageId")));
			labelName = CommonUtils.getString(request.getParameter("labelName"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messageId < 1 || StringUtils.isBlank(labelName)) {
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		SysLabel label = labelService.get(userId, labelName);
		if (label == null || label.getId() < 1) {
			return JSON.toJSONString(new ResultBean(0, "标签不存在", null));
		}
		try {
			SysMessageDrafts message = messageDraftsService.get(messageId, userId);
			SysLabelMessage labelMessage = labelMessageService.get(userId, label.getId() + "", message.getId() + "",
					folderName);
			if (labelMessage != null && labelMessage.getId() > 0) {
				labelMessageService.delete(labelMessage.getId(), userId);
			}
			if (CommonUtils.getString(message.getLabel()).contains(label.getName().trim())) {
				String[] labels = message.getLabel().trim().split(",");
				ArrayList<String> labelList = new ArrayList<String>();
				for (int i = 0; i < labels.length; i++) {
					if (!labels[i].trim().equalsIgnoreCase(label.getName().trim())) {
						labelList.add(labels[i].trim());
					}
				}
				message.setLabel(StringUtils.join(labelList, ","));
				messageDraftsService.update(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(0, "移除失败", null));
		}
		return JSON.toJSONString(new ResultBean(1, "移除成功", null));
	}

}
